package org.qydjk.console.controller.company;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.company.Company;
import org.qydjk.common.pojo.Dept;
import org.qydjk.common.pojo.Employee;
import org.qydjk.common.pojo.user.User;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.ExcelUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.common.vo.autocomplete.AutoCompleteBean;
import org.qydjk.common.vo.autocomplete.AutoCompleteResponse;
import org.qydjk.console.service.ICompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/company")
public class CompanyController extends BaseController {
    @Autowired
    private ICompanyService companyService;

    @RequestMapping("/gotoPage.do")
    public String gotoPage(){
        return "company/company";
    }

    @RequestMapping("/companydg.do")
    @ResponseBody
    public Object companydg(Integer page, Integer rows,String name,Integer type){
        List<Company> companyList = new ArrayList<Company>();
        try {
            HibernatePage pager = new HibernatePage(page, rows);
            String sql = "select * from qy_company where 1=1";
            String countsql = "select count(*) from qy_company where 1=1";
            if(type!=null){
                sql+=" and type ="+type;
                countsql+=" and type ="+type;
            }
            if(!StringUtil.isEmptyOrNull(name)){
                sql+=" and name like '%"+name+"%'";
                countsql+=" and name like '%"+name+"%'";
            }
            companyList= baseService.findBeanBySQL(sql,Company.class,pager);
            int total = baseService.getRecordCountSQL(countsql);
            return new EasyUIResponse(total, companyList);
        } catch (Exception e) {
            e.printStackTrace();
            return new EasyUIResponse(0, companyList);
        }
    }

    /**
     * 员工列表
     * @param page
     * @param rows
     * @param companyId
     * @param sex
     * @return
     */
    @RequestMapping("/employeedg.do")
    @ResponseBody
    public Object employeedg(Integer page, Integer rows,Integer companyId,Integer sex,String name,Integer deptId){
        List<Employee> companyList = new ArrayList<Employee>();
        try {
            HibernatePage pager = new HibernatePage(page, rows);
            String sql = "select * from qy_employee where company_id = "+companyId;
            String countsql = "select count(*) from qy_employee where company_id = "+companyId;
            if(deptId!=null){
                sql+=" and dept_id = "+deptId;
                countsql+=" and dept_id = "+deptId;
            }
            if(sex!=null){
                sql+=" and sex ="+sex;
                countsql+=" and sex ="+sex;
            }
            if(!StringUtil.isEmptyOrNull(name)){
                sql+=" and name like '%"+name+"%'";
                countsql+=" and name like '%"+name+"%'";
            }
            companyList= baseService.findBeanBySQL(sql,Employee.class,pager);
            int total = baseService.getRecordCountSQL(countsql);
            return new EasyUIResponse(total, companyList);
        } catch (Exception e) {
            e.printStackTrace();
            return new EasyUIResponse(0, companyList);
        }
    }
    /*企业部门表*/
    @RequestMapping("/deptdg.do")
    @ResponseBody
    public Object deptdg(Integer companyId){
        List<Map<String,Object>> companyList = new ArrayList<Map<String, Object>>();
        try {
            String sql = "select * from qy_dept where company_id = "+companyId;
            String countsql = "select count(*) from qy_dept where company_id = "+companyId;
            companyList= baseService.findMapBySQL(sql);
            int total = baseService.getRecordCountSQL(countsql);
            return new EasyUIResponse(total, companyList);
        } catch (Exception e) {
            e.printStackTrace();
            return new EasyUIResponse(0, companyList);
        }
    }
    /**
     * 自动补全 用户信息
     *
     * @author Edward_yang
     * @uptime 2017-12-20
     */
    @RequestMapping("/autoCompleteData.do")
    @ResponseBody
    public Object sellerUserAutoCompleteData() {
        List<AutoCompleteBean> list = new ArrayList<AutoCompleteBean>();
        String query = request.getParameter("query");
        if (StringUtil.isEmptyOrNull(query)) {
            return new AutoCompleteResponse(list);
        }
        String sql = "SELECT concat(username) AS `value`,concat(id,'') AS `data` FROM qy_user WHERE   type=4 and (phone LIKE '%" + query + "%' OR username LIKE '%" + query + "%')";
        try {
            list = baseService.findBeanBySQL(sql, AutoCompleteBean.class, new HibernatePage(1, 10));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AutoCompleteResponse(list);
    }

    /**
     * 添加企业
     * @param company
     * @return
     */
    @RequestMapping("/add.do")
    @ResponseBody
    public Object add(Company company){
        try {
            baseService.saveOrUpdate(company);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }
    /*删除企业*/
    @RequestMapping("/delete.do")
    @ResponseBody
    public Object delete(Integer id){
        try {
            companyService.delCompany(id);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }
    /**
     * 编辑企业
     * @param company
     * @return
     */
    @RequestMapping("/edit.do")
    @ResponseBody
    public Object edit(Company company){
        try {
            int id = company.getId();
            Company old = baseService.get(Company.class,id);
            BeanUtil.copyProperties(company,old);
            baseService.saveOrUpdate(old);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }
    /**
     * 根据用户ID查询用户名称
     */
    @RequestMapping("/getUserName.do")
    @ResponseBody
    public String getUserName(Integer id) {
        User user = new User();
        try {
            if(id==null) return "";
            user = baseService.get(User.class,id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user.getUsername();
    }
    /**
     * 添加部门
     */
    @RequestMapping("/addDept.do")
    @ResponseBody
    public Object addDept(String name,Integer deptId,Integer companyId){
        try {
            Dept dept = new Dept();
            dept.setName(name);
            dept.setCompanyId(companyId);
            dept.setId(deptId);
            if(deptId!=null){
                String sql = "update qy_employee set deptname = '"+name+"' where dept_id = "+deptId;
                baseService.excuteSQL(sql);
            }
            baseService.saveOrUpdate(dept);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }
    /**
     * 删除部门
     */
    @RequestMapping("/delDept.do")
    @ResponseBody
    public Object delDept(Integer id){
        try {
            companyService.delDept(id);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /**
     * 添加或修改一个员工
     * @param employee
     * @return
     */
    @RequestMapping("/addEmployee.do")
    @ResponseBody
    public Object addEmployee(Employee employee){
        try{
            if(employee.getId()!=null){
                baseService.saveOrUpdate(employee);
                return renderSuccess();
            }
            String  res = companyService.addEmpany(employee);
            if(!"OK".equals(res)){
                return renderError("员工"+res+"信息有重复,请检查身份证号、电话、邮箱是否正确。");
            }else{
                return renderSuccess();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /**
     * 批量添加员工
     * @return
     */
    @RequestMapping("/addEmployeeFromExcel.do")
    @ResponseBody
    public Object addEmployeeFromExcel(){
        try{
            //创建工厂
            DiskFileItemFactory factoy=new DiskFileItemFactory();
            //创建解析器
            ServletFileUpload sfu=new ServletFileUpload(factoy);
            //解析request
            List<FileItem> list=sfu.parseRequest(request);
            Map<String, Object> datas = new HashMap<String, Object>();
            String companyId = "";
            String deptId = "";
            String deptname = "";
            for (FileItem item:  list){
                if(item.getFieldName().equals("companyId")){
                    companyId = item.getString("utf-8");
                } if(item.getFieldName().equals("deptId")){
                    deptId = item.getString("utf-8");
                }if(item.getFieldName().equals("deptname")){
                    deptname = item.getString("utf-8");
                }if(item.getFieldName().equals("excelFile")){
                    datas = ExcelUtil.getDataFromExcel(item.getInputStream());
                }
            }
            if(!"OK".equals(datas.get("msg"))){
                return renderError(datas.get("msg").toString());
            }
            Employee employee = new Employee();
            employee.setCompanyId(Integer.parseInt(companyId));
            employee.setDeptId(Integer.parseInt(deptId));
            employee.setDeptname(deptname);
            String res =  companyService.addEmpanyByExcel(employee, (List<Map<String, Object>>) datas.get("content"));
            if(!"OK".equals(res)){
                return renderError("员工"+res+"信息有重复,请检查身份证号、电话、邮箱是否正确。");
            }else{
                return renderSuccess();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /**
     * 删除一个员工
     * @param id
     * @return
     */
    @RequestMapping("/delEmployee.do")
    @ResponseBody
    public Object delEmployee(Integer id){
        try{
            Employee employee = baseService.get(Employee.class,id);
            baseService.delete(employee);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }
}
